package com.djf.djfauth.controller;

import com.djf.djfauth.entity.LoginVO;
import com.djf.djfauth.entity.User;
import com.djf.djfauth.entity.UserAuth;
import com.djf.djfauth.service.UserAuthService;
import com.djf.djfauth.service.UserService;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 26393
 * @Date 2025/7/7 2:21
 * @Version 1.0
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {

    @Resource
    @Qualifier("qqAuthConfig")
    private AuthConfig qqAuthConfig;
    @Resource
    @Qualifier("weixinAuthConfig")
    private AuthConfig weixinAuthConfig;
    @Resource
    @Qualifier("dingtalkAuthConfig")
    private AuthConfig dingtalkAuthConfig;
    @Resource
    @Qualifier("giteeAuthConfig")
    private AuthConfig giteeAuthConfig;

    @Resource
    private UserAuthService userAuthService;
    @Resource
    private UserService userService;

    @GetMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) throws Exception {
        AuthRequest authRequest = getAuthRequest(type);
        String authorizeUrl = authRequest.authorize("state-" + type + System.currentTimeMillis());

        response.sendRedirect(authorizeUrl);

        System.out.println(authorizeUrl);
    }

    @GetMapping("/callback/{type}")
    public LoginVO callback(@PathVariable String type, AuthCallback callback) {

        System.out.println("回调信息"+callback);
        AuthRequest authRequest = getAuthRequest(type);
        AuthResponse<AuthUser> response = authRequest.login(callback);
        if (!response.ok()) throw new RuntimeException("第三方授权失败：" + response.getMsg());
        AuthUser authUser = response.getData();
        //把用户里面的信息都打印出来
        System.out.println("=== 第三方用户信息详情 ===");
        System.out.println("用户ID: " + authUser.getUuid());
        System.out.println("用户名: " + authUser.getUsername());
        System.out.println("昵称: " + authUser.getNickname());
        System.out.println("头像: " + authUser.getAvatar());
        System.out.println("邮箱: " + authUser.getEmail());
        System.out.println("性别: " + authUser.getGender());
        System.out.println("来源: " + authUser.getSource());
        System.out.println("原始用户信息: " + authUser.getRawUserInfo());
        System.out.println("访问令牌: " + authUser.getToken());
        System.out.println("========================");


        // 查找三方账号
        UserAuth userAuth = userAuthService.findByTypeAndOpenId(type, authUser.getUuid());
        User user;
        if (userAuth != null) {
            user = userService.findById(userAuth.getUserId());
        } else {
            // 新用户，自动注册
            Long userId = userService.createUser(type + "_" + authUser.getUuid(), authUser.getNickname(), authUser.getAvatar());
            userAuthService.createUserAuth(userId, type, authUser.getUuid(), authUser.getNickname(), authUser.getAvatar());
            user = userService.findById(userId);
        }

        LoginVO vo = new LoginVO();
        vo.setUserId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setNickname(user.getNickname());
        vo.setAvatar(user.getAvatar());
        return vo;
    }

    private AuthRequest getAuthRequest(String type) {
        switch (type) {
            case "qq": return new AuthQqRequest(qqAuthConfig);
            //微信的
            case "weixin": return new AuthWeChatMpRequest(weixinAuthConfig);
            //钉钉的
            case "dingtalk": return new AuthDingTalkRequest(dingtalkAuthConfig);
            case "gitee": return new AuthGiteeRequest(giteeAuthConfig);
            default: throw new IllegalArgumentException("不支持的类型: " + type);
        }
    }
}